package org.phalanx.servlet.websession;

import java.util.ArrayList;
import java.util.Iterator;

import org.phalanx.messenging.AbstractMessage;
import org.phalanx.messenging.MessageFeedListener;
import org.phalanx.messenging.Messageable;
import org.phalanx.server.PhalanxServer;
import org.phalanx.server.ServerCache.CacheManager;
import org.phalanx.server.ServerCache.Cacheable;
import org.phalanx.server.game.GameMembers;

public class GameFeed implements Cacheable, MessageFeedListener{
	protected Integer gameId;
	protected ArrayList<Integer> userFeedList;
	
	public GameFeed(Integer gameId){
		this.setId(gameId);
		userFeedList = new ArrayList<Integer>();
	}
	
	public void addUserToFeed(Integer uId){
		CacheManager cacheMgr = PhalanxServer.getServerInstance().getCacheManager();
		
		GameMembers userMember = (GameMembers)cacheMgr.getElement("UserGameCache", uId);
		
		if (userMember != null &&  userMember.getGameIds().contains(gameId)){
			// checks if the user is a member of the respective game before assigning a feed
			
			if (!userFeedList.contains(uId)){
				userFeedList.add(uId);
			}
		}
	}
	
	public void removeUserFromFeed(Integer uId){
		CacheManager cacheMgr = PhalanxServer.getServerInstance().getCacheManager();
		
		GameMembers userMember = (GameMembers)cacheMgr.getElement("UserGameCache", uId);
		
		if (userMember != null &&  userMember.getGameIds().contains(gameId)){
			if (userFeedList.contains(uId)){
				userFeedList.remove(uId);
			}
		}
	}
	
	public void sendGameDataToFeed(Messageable msg){
		// Sends to all users on feed
		CacheManager cacheMgr = PhalanxServer.getServerInstance().getCacheManager();
		Iterator<Integer> i = userFeedList.iterator();
		
		while (i.hasNext()){
			Integer currentUserId = i.next();
			
			UserWebSession session = (UserWebSession)cacheMgr.getElement("UserWebFeedCache", currentUserId);
			
			if (session != null){
				session.sendMessage(msg);
			}
		}
	}
	
	public void sendGameDataToFeed(Messageable msg, Integer uid){
		// Sends to a specific user
		CacheManager cacheMgr = PhalanxServer.getServerInstance().getCacheManager();

		UserWebSession session = (UserWebSession)cacheMgr.getElement("UserWebFeedCache", uid);

		if (session != null){
			session.sendMessage(msg);
		}
	}
	
	public void clearFeed(){
		userFeedList.clear();
	}

	@Override
	public Integer getId() {
		return gameId;
	}

	@Override
	public void setId(Integer id) {
		this.gameId = id;
	}

	@Override
	public ArrayList<Integer> getUsers() {
		// TODO Auto-generated method stub
		return userFeedList;
	}

}
